package com.github.m6d21.sso.service.role.impl;

import com.github.m6d21.sso.dao.role.dao.IUnionRoleDao;
import com.github.m6d21.sso.model.role.dto.RolePermissionDTO;
import com.github.m6d21.sso.model.role.qo.RolePermissionQO;
import com.github.m6d21.sso.model.role.vo.UnionRole;
import com.github.m6d21.sso.service.role.IUnionRoleService;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2019/1/4 Fri 17:19:00
 * @since 1.0.0
 */
@Service("unionRoleService")
public class UnionRoleServiceImpl implements IUnionRoleService {

    @Resource
    private IUnionRoleDao unionRoleDao;

    @Override
    public List<UnionRole> unionQuery(RolePermissionQO rolePermissionQO) {
        List<UnionRole> unionRoleList = unionRoleDao.unionQuery(rolePermissionQO);
        return Optional.ofNullable(unionRoleList).orElse(new ArrayList<>(0));
    }

    @Override
    public Boolean saveRolePermissionRelation(RolePermissionDTO rolePermissionDTO) {
        return unionRoleDao.insertRolePermissionRelation(rolePermissionDTO);
    }

    @Override
    public void saveBatchRolePermissionRelation(List<RolePermissionDTO> rolePermissionDTOList) {
        unionRoleDao.insertBatchRolePermissionRelation(rolePermissionDTOList);
    }

    @Override
    public void deleteBatchRolePermissionRelation(Integer roleId, List<Integer> permissionIds) {
        unionRoleDao.deleteBatchRolePermissionRelation(roleId, permissionIds);
    }

    @Transactional
    @Override
    public void allocPermissions(Integer roleId, List<Integer> allocPermissionIds, List<Integer> deletePermissionIds) {
        if (roleId == null) {
            return;
        }

        //删除移除的权限
        if (CollectionUtils.isNotEmpty(deletePermissionIds)) {
            unionRoleDao.deleteBatchRolePermissionRelation(roleId, deletePermissionIds);
        }
        //分配新增的权限
        if (CollectionUtils.isNotEmpty(allocPermissionIds)) {
            List<RolePermissionDTO> rolePermissionDTOList = new ArrayList<>(allocPermissionIds.size());
            allocPermissionIds.forEach(permissionId -> {
                RolePermissionDTO rolePermissionDTO = new RolePermissionDTO();
                rolePermissionDTO.setRoleId(roleId);
                rolePermissionDTO.setPermissionId(permissionId);
                rolePermissionDTOList.add(rolePermissionDTO);
            });
            int row = unionRoleDao.insertBatchRolePermissionRelation(rolePermissionDTOList);
        }
    }
}
